<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2018/12/17
 * Time: 下午5:39
 */

namespace App\Lib;

use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Http\RequestCore;
use OSS\Http\ResponseCore;

class oss
{
    private $accesskeyid;
    private $accesskeysecret;
    private $endpoint;
    private $bucket;

    public function __construct(){
        $this->accesskeyid = config("oss.accesskeyid");
        $this->accesskeysecret = config("oss.accesskeysecret");
        $this->endpoint = config("oss.endpoint");
        $this->bucket = config("oss.bucket");
    }
    
    /**
     * 生成客户端上传图片的临时url
     * @param $uri     oss上的路径 users/pic/1212/600eeac2b13fb7a597004e1f216840e2.png
     * @return string  客户端上传的的零时url
     */
    public function get_object_put_url($uri){
        $timeout = 3600;
        try {
            $ossClient = new OssClient($this->accesskeyid, $this->accesskeysecret, $this->endpoint, false);
            $signedUrl = $ossClient->signUrl($this->bucket, $uri, $timeout, "PUT");
        } catch (OssException $e) {
            //printf(__FUNCTION__ . ": FAILED\n");
            //printf($e->getMessage() . "\n");
            return "";
        }
        return $signedUrl;
    }


    public function frozenObject($uri)
    {
        if ($uri[0] == '/'){
            $uri = ltrim($uri, '/');
        }
        try {
            $ossClient = new OssClient($this->accesskeyid, $this->accesskeysecret, $this->endpoint, false);
            $ossClient->putObjectAcl($this->bucket, $uri, 'private');
        } catch (OssException $e) {
            //printf(__FUNCTION__ . ": FAILED\n");
        //    printf($e->getMessage() . "\n");
            return false;
        }
        return true;
    }
    
    public function getAs($signedUrl,$content){
        $request = new RequestCore($signedUrl);
        // 生成的URL以PUT方式访问。
        $request->set_method('PUT');
        $request->add_header('Content-Type', '');
//        $request->add_header('Content-Length', $size);
        $request->set_body($content);
        $request->send_request();
        $res = new ResponseCore($request->get_response_header(), $request->get_response_body(), $request->get_response_code());

        if ($res->isOK()) {
            return true;
        } else {
           return false;
        }
    }

    /**
     * 上传文件
     *
     * @param string $fileName 文件名称
     * @param string $filePath 本地文件地址
     * @return bool
     */
    public function uploadFile(string $fileName, string $filePath): bool
    {
        try{
            $ossClient = new OssClient($this->accesskeyid, $this->accesskeysecret, $this->endpoint);
            $ossClient->uploadFile($this->bucket, $fileName, $filePath);
            @unlink($filePath);
            return true;
        } catch(OssException $e) {
            @unlink($filePath);
            return false;
        }
    }

}